<template>
  <div id="student">
    <div class="main">
      <h2>智能学习助手</h2>
      <div class="chat-container">
        <!-- 左侧历史对话列表 -->
        <div class="chat-sidebar">
          <el-button type="primary" @click="startNewChat" icon="Plus">新对话</el-button>
          <ul class="chat-history">
            <li
              v-for="chat in chatList"
              :key="chat.chatID"
              :class="{ active: chat.chatID === currentChatId }"
              @click="loadChat(chat.chatID)"
            >
              {{ chat.content.slice(0, 12) }}{{ chat.content.length > 12 ? '...' : '' }}
              <i class="el-icon-delete" @click.stop="deleteChat(chat.chatID)"></i>
            </li>
          </ul>
        </div>

        <!-- 右侧对话窗口 -->
        <div class="chat-main">
          <div class="chat-log" v-if="chatLog.length">
            <div
              v-for="(msg, index) in chatLog"
              :key="index"
              :class="msg.speaker === 1 ? 'chat-user' : 'chat-ai'"
            >
              <span class="chat-content">{{ msg.content }}</span>
            </div>
          </div>
          <div v-else class="chat-empty">请开始新的对话或选择左侧历史记录</div>

          <!-- 输入框和按钮 -->
          <div class="chat-input">
            <el-input
              v-model="inputContent"
              placeholder="请输入问题"
              @keyup.enter="sendMessage"
              clearable
            />
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </div>
        </div>
      </div>
    </div>

    <RouterView />
    <my-footer />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useCookies } from 'vue3-cookies'

const {cookies} = useCookies()

const store = useStore()
const route = useRoute()
const router = useRouter()

const flag = ref(false)
const user = ref({ userName: '', studentId: '' })
const courseId = ref('')
const chatList = ref([])
const currentChatId = ref(null)
const chatLog = ref([])
const inputContent = ref('')
const sending = ref(false)

const isPractice = computed(() => store.state.isPractice)

async function userInfo() {
  const name = cookies.get('cname') || ''
  const id = cookies.get('cid') || ''
  user.value = { userName: name, studentId: id }
}

async function loadChatList() {
  const res = await axios.get('/api/chat/chatlist', {
    params: {
      studentID: user.value.studentId,
      courseID: courseId.value
    }
  })
  if (res.data.code === 200) {
    chatList.value = res.data.data
    if (chatList.value.length > 0 && !currentChatId.value) {
      loadChat(chatList.value[0].chatID)
    }
  }
}

async function startNewChat() {
  const res = await axios.get('/api/chat/newchatid', {
    params: {
      studentID: user.value.studentId,
      courseID: courseId.value
    }
  })
  if (res.data.code === 200) {
    currentChatId.value = res.data.data
    chatLog.value = []
    inputContent.value = ''
    await loadChatList()
  }
}

async function loadChat(chatID) {
  currentChatId.value = chatID
  const res = await axios.get('/api/chat/chatlog', {
    params: {
      studentID: user.value.studentId,
      courseID: courseId.value,
      chatID: chatID
    }
  })
  if (res.data.code === 200) {
    chatLog.value = res.data.data
    await nextTick()
    scrollToBottom()
  }
}

function scrollToBottom() {
  nextTick(() => {
    const el = document.querySelector('.chat-log')
    if (el) el.scrollTop = el.scrollHeight
  })
}

async function sendMessage() {
  if (sending.value || !inputContent.value.trim() || !currentChatId.value) return
  sending.value = true

  const userMessage = inputContent.value.trim()
  chatLog.value.push({ speaker: 1, content: userMessage })
  inputContent.value = ''
  await nextTick()
  scrollToBottom()

  const studentID = user.value.studentId
  const courseID = courseId.value
  const chatID = currentChatId.value
  let aiReply = ''
  chatLog.value.push({ speaker: 2, content: aiReply })
  await nextTick()
  scrollToBottom()

  try {
    const params = new URLSearchParams({ courseID, studentID, chatID, content: userMessage })
    const es = new EventSource(`/api/chat/query?${params.toString()}`)

    es.onmessage = async (event) => {
      let incoming = event.data
      if (/^[a-zA-Z]+$/.test(incoming) && /[a-zA-Z]$/.test(aiReply)) {
        incoming = ' ' + incoming
      }
      aiReply += incoming
      chatLog.value[chatLog.value.length - 1].content = aiReply
      await nextTick()
      scrollToBottom()
    }

    es.onerror = () => {
      es.close()
      sending.value = false
      if (!aiReply) {
        chatLog.value.pop()
        ElMessage.error('AI 回复失败')
      }
      loadChatList()
    }

    es.addEventListener('done', () => {
      es.close()
      sending.value = false
      const idx = chatList.value.findIndex(c => c.chatID === currentChatId.value)
      if (idx !== -1) {
        chatList.value[idx].content = aiReply
      }
      loadChatList()
    })
  } catch (e) {
    sending.value = false
    chatLog.value.pop()
    ElMessage.error('连接失败')
  }
}

async function deleteChat(chatID) {
  try {
    await ElMessageBox.confirm('确定要删除该对话记录吗？', '提示', {
      confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning'
    })
    await axios.delete('/api/chat/delete', { params: {
      courseID: courseId.value,
      studentID: user.value.studentId,
      chatID: chatID
    }})
    if (chatID === currentChatId.value) {
      currentChatId.value = null
      chatLog.value = []
    }
    await loadChatList()
    ElMessage.success('删除成功')
  } catch {}
}

function manage() {
  router.push('/student/manage')
}

function exit() {
  Cookies.remove('cname')
  Cookies.remove('cid')
  router.push('/login')
}

onMounted(async () => {
  await userInfo()
  const stored = cookies.get('selectedCourse')
  courseId.value = stored.id
  await loadChatList()
})
</script>

<style scoped>
.right .icon {
  margin-right: 6px;
}
#student .padding-50 {
  margin: 0 auto;
  padding: 0 50px;
  box-shadow: 0 0 10px 4px rgba(1, 149, 255, 0.1);
  background-color: #fff;
}
.list a {
  text-decoration: none;
  color: #334046;
}
li {
  list-style: none;
  height: 60px;
  line-height: 60px;
}
#student .list {
  display: flex;
}
#student .list li {
  padding: 0 20px;
  cursor: pointer;
}
#student .list li:hover {
  background-color: #0195ff;
  transition: all 0.3s ease;
}
#student .list li:hover a {
  color: #fff;
}
#student .list .right {
  margin-left: auto;
  position: relative;
}
#student .list li.right:hover a {
  color: #000;
}
#student .list .logo {
  display: flex;
  font-weight: bold;
  color: #2f6c9f;
}
#student .list .logo i {
  font-size: 50px;
}
.right .msg {
  text-align: center;
  position: absolute;
  top: 60px;
  right: 0;
  display: flex;
  flex-direction: column;
  border-radius: 2px;
  border-bottom: 3px solid #0195ff;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}
.right .msg p {
  height: 40px;
  line-height: 40px;
  width: 105px;
}
.right .msg p:hover {
  background-color: #0195ff;
  color: #fff;
}
.main {
  padding: 20px 50px;
  /* background-color: #f9f9f9; */
  min-height: 500px; /* Added for better layout */
}

.file-link {
  color: #409EFF;
  cursor: pointer;
}

.file-link:hover {
  text-decoration: underline;
}

.dialog-footer {
  text-align: right;
}

.empty-hint {
  padding: 30px;
  text-align: center;
  color: #999;
  font-size: 16px;
}
.chat-container {
  display: flex;
  height: 600px;
  border: 1px solid #e4e4e4;
  background: #fff;
}
.chat-sidebar {
  width: 250px;
  border-right: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box;
  background: #f6f8fa;
  overflow-y: auto; /* ✅ 添加滚动 */
}
.chat-history {
  list-style: none;
  padding: 0;
  margin-top: 10px;
}
.chat-history li {
  padding: 8px;
  border-bottom: 1px solid #ddd;
  cursor: pointer;
  position: relative;
}
.chat-history li.active {
  background: #dbeeff;
}
.chat-history li:hover {
  background: #ecf5ff;
}
.chat-history i {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: red;
}
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%; /* ✅ 保持撑满父容器 */
}
.chat-log {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.chat-user {
  text-align: right;
  margin-bottom: 10px;
}
.chat-ai {
  text-align: left;
  margin-bottom: 10px;
}
.chat-content {
  display: inline-block;
  max-width: 70%;
  padding: 10px;
  border-radius: 10px;
  background: #e1f3ff; /* 默认是 AI 的背景 */
}

/* 学生（用户）发出的消息是蓝色 */
.chat-user .chat-content {
  background: #cdefff;
}

/* AI 回复的消息改为白色框 */
.chat-ai .chat-content {
  background: #e7e7e7;
  
}
.chat-input {
  padding: 10px;
  border-top: 1px solid #ccc;
  display: flex;
  gap: 10px;
}
.chat-empty {
  padding: 30px;
  color: #888;
  text-align: center;
}
</style>
